# -*- coding:utf-8 -*-
from __future__ import division
from dao.MySqlDAL import MySqlDAL
from collections import defaultdict
import numpy as np
__author__ = 'shudongma.msd(风骐)'

sqlUtil = MySqlDAL()
def getRankInfo(strdate):
    """
        获取某天的排行榜数据
    """
    global sqlUtil
    res = sqlUtil.get_dimensions_rows("select type,stock_id,num from tb_share_rank where date = '"+strdate+"'")
    '''
        rank_dict 设计：
            {
                'stock_id':{'$type':'标准化后的num',...},
            }
    '''
    rank_dict = defaultdict(dict)
    num_list = defaultdict(list)
    for row in res:
        rank_dict[row['stock_id']][str(row['type'])] = row['num']
        num_list[str(row['type'])].append(row['num'])
    # min-max标准化
    for k,v in num_list.iteritems():
        min_num = min(v)
        max_num = max(v)
        num_list[k] = [min_num,max_num]
    for value in rank_dict.values():
        for k in value:
            value[k] = (value[k]-num_list[k][0])/(num_list[k][1]-num_list[k][0])
    # Z-score标准化方法
    # for k,v in num_list.iteritems():
    #     mean_num = np.mean(v)
    #     std_num = np.std(v)
    #     num_list[k] = [mean_num,std_num]
    # for value in rank_dict.values():
    #     for k in value:
    #         value[k] = (value[k]-num_list[k][0])/num_list[k][1]
    return rank_dict

# s = sorted(getRankInfo('2015-09-25').iteritems(),key=lambda b : b[1]['0'],reverse=True)
#
# for k,v in  s:
#     # if k=='SH600886':
#     print k,v


# import datetime
#
# def getRankInfo(strdate):
#     """
#         获取某天的排行榜数据
#     """
#     global sqlUtil
#     res = sqlUtil.get_dimensions_rows("select type,stock_id,num from tb_share_rank where date = '"+strdate+"'")
#     date2 = datetime.datetime.strptime(strdate, "%Y-%m-%d").date() - datetime.timedelta(days=1)
#     res2 = sqlUtil.get_dimensions_rows("select type,stock_id,num from tb_share_rank where date = '"+str(date2)+"'")
#
#     rank_dict = defaultdict(dict)
#
#     for row in res:
#         rank_dict[row['stock_id']][str(row['type'])] = row['num']
#
#     # 排行榜数量变化
#     for row in res2:
#         try:
#             rank_dict[row['stock_id']][str(row['type'])] -= row['num']
#         except:
#             rank_dict[row['stock_id']][str(row['type'])] = 0
#     return rank_dict